#include "p_additem.h"
#include "ui_p_additem.h"

P_AddItem::P_AddItem(QWidget *parent,
                     const QStringList &categories) :
    QDialog(parent),
    ui(new Ui::P_AddItem)
{
    ui->setupUi(this);

    _id=-1;
    if(categories.isEmpty())
        ui->categories->setEnabled(false);
    else {
        ui->categories->addItems(categories);
        ui->categories->addItem(MANUAL_INPUT);
        ui->categories->setCurrentIndex(-1);
    }
}

P_AddItem::~P_AddItem()
{
    delete ui;
}

void P_AddItem::setItem(int id,
                        const QString &category,
                        const QString &detail)
{
    _id=id;
    _category=category;
    _detail=detail;

    ui->btn_submit->setText("保存");
    ui->category->setText(category);
    ui->detail->setPlainText(detail);
}

void P_AddItem::on_categories_currentTextChanged(const QString &category)
{
    if(category == MANUAL_INPUT)
    {
        ui->category->setEnabled(true);
        ui->category->clear();
    }
    else {
        ui->category->setText(category);
        ui->category->setEnabled(false);
    }
}

void P_AddItem::on_btn_submit_clicked()
{
    QString category=ui->category->text().trimmed();
    if(category.isEmpty())
    {
        MESSAGE_CATEGORY_EMPTY
    }

    QString detail=ui->detail->toPlainText().trimmed();
    if(detail.isEmpty())
    {
        MESSAGE_DETAIL_EMPTY
    }

    QJsonObject obj;
    if(_id > 0)
    {

        if(category != _category)
            obj.insert("category",category);

        if(detail != _detail)
            obj.insert("detail",detail);

        if(obj.isEmpty())
            return;

        obj.insert("id",_id);
        emit updateItem(obj);
    }
    else {
        obj.insert("category",category);
        obj.insert("detail",detail);
        emit addItem(obj);
    }
    accept();
}
